<template>
  <el-cascader :value="value" :options="options" separator="-" placeholder="请选择部门" clearable :props="props" @change="submit">
    <template slot-scope="{ node, data }">
      <span>{{ data.name }}</span>
      <span v-if="!node.isLeaf"> ({{ data.children.length > 0 ? data.children.length: null }}) </span>
    </template>
  </el-cascader>
</template>

<script>
import { getDepartments } from '@/api/department'
import { remove } from 'nprogress'
// import { getTree } from '@/utils'
export default {
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      options: [],
      id: null,
      props: { value: 'id', label: 'name' }
    }
  },
  created() {
    this.getDepartmentsFn()
  },
  methods: {
    getTree(res, id) {
      const arr = []
      res.forEach(item => {
        if (item.pid === id) {
          const children = this.getTree(res, item.id)
          if (children.length > 0) {
            item.children = children
          } else {
            remove(item.children)
          }
          arr.push(item)
        }
      })
      return arr
    },
    async getDepartmentsFn() {
      const res = await getDepartments()
      this.options = this.getTree(res, 0)
      console.log(this.options)
    },
    async submit(value) {
      console.log(value)
      if (value.length > 0) {
        this.$emit('input', value[value.length - 1])
      } else {
        this.$emit('input', null)
      }
    }
  }
}
</script>
